(function($,window,document,undefined){
	'use strict';
	$.fn.lancesOperationsInitialize = function(o){
		  var op = {url:!1},
		      initialize  =true;
		  
		  

		    $('.btn-ico').on('click',function(){
		    	$(this).find('i').toggleClass('i-on');
		    	
		    });
		    
		   
		    $('.bid-click').off('click').on('click',function(e){
		    	e.preventDefault();
		       $('.bid-click').removeClass('is-active');
		       $(this).addClass('is-active');
               var $id = $(this).attr('bid-id');

               $('[data-lote-id="'+$id+'"]').find('.btn-lance-aut').addClass('on');
		    });
		    
		    $('[resetBids]').off('click').on('click',function(e){
		    	e.preventDefault();
		        $('.bid-click').removeClass('is-active');
		        $('.bid-click').eq(0).addClass('is-active');
		     });
		    
		    
		    $('[add-lance-automatic]').off('click.LanceAutomatico').on('click.LanceAutomatico',function(e){
		    	 e.preventDefault();
		    	 
		    	 var $u_id  = $(this).attr('u-id'),
		    	     $l_id  = $(this).attr('l-id'),
		    	     $lt_id = $(this).attr('lt-id'),
		    	     $has_class= $(this).attr('class'),
		    	     pattern  = /HGA/gi;
		    	 
		    	 $.fancybox({
		    		 type:'ajax',
		    		 width:250,
                                 height:270,
                                 scrolling:'no',
		    		 autoResize  : false,
                                 autoSize : false,
		    		 href:url_site + 'showAutoLance-' + $u_id +'-'+ $l_id +'.html',
		    		 afterLoad	:	function() {
		    			 setInterval($.fn.initLanceAuto,100);
		    			}
		    	 });
		    });
		    
		    $('[no-lance-user]').on('click',function(e){
		    	e.preventDefault();
		    	showBoxInfo('Esse usuário não tem permissão para realizar essa operação.<br/> Verifique sua situação cadastral.');
		    });
		  /**
		   * Add Lance in lote
		   * 
		   */
		  $('[addLance]').off('click.AddLance').on('click.AddLance',function(e) {
		        e.preventDefault();
		        var id = $(this).attr('lance-lote-id'),
		                objCount = $('.lote-'+ id+''),
		                sd = objCount.attr('data-count'),
		                $data =  sd.split(/[\s\-:]/gi),
		                $hours = 0,
		                $dates = new Date(),
                        $isActive =  $('[data-lote-id="'+id+'"]').find('.bid-click.is-active'),                             
                        $autoLanceVal = $isActive.attr('ival') || 0, 
                        $autoLance = $isActive.attr('ival') ? true : false ;
                        
		               
		               
		        if($data.length == 0){ return false;}
		               //sum + minutes extra
		               var sum_m = parseInt($data['4'], 10) + 3;
		                   sum_m = sum_m < 10 ? '0' + sum_m : sum_m;
		                 $hours = $data.slice(3).join(':');
		                 $dates = $data.slice(0,3).join('-');
		                 objCount.attr('data-count', $dates+' '+$hours );
		             var newYear = new Date(),
		                 minutes_sec = minutes * 60,
		                 inewYear = new Date(newYear.getFullYear(), 
		                		        newYear.getMonth(), 
		                		        newYear.getDate(), 
		                		        newYear.getHours(), 
		                		        newYear.getMinutes() + 3);


		        if (onTicker['painel-data-' + id] < minutes_sec) {
		            $('#painel-online-' + id).removeClass('red');
		            //reset plus time
		            $('.lote-'+ id).countdown('option', {until: +minutes_sec});

		        }
		        
		        addLance(this);

		    });
		  
		  

		  function addLance(obj) {
		      var     $id = $(obj).attr('lance-lote-id'),
		              date_ativo_finish = $(this).attr('data-lance-lote'),
		              minutes_sec = minutes * 60,
		              upd = onTicker['data-' + $id] < minutes_sec ? 'yes' : 'no',
		              $isActive =  $('[data-lote-id="'+$id+'"]').find('.bid-click.is-active'),                             
                      $autoLanceVal = $isActive.attr('ival') || 0, 
                      $autoLance = $isActive.attr('ival') ? true : false ;

		      $.onTickerleilao.tickers_stamp[$id] = false;
		      if (upd === 'yes') {
		          var $mktime = mktime(date('H'), date('i'), date('s'), date('m'), date('d'), date('Y'));
		          $.onTickerleilao.tickers_stamp[idLt] = date('Y-m-d H:i:s', $mktime);
		      }

		      if ($.isAjaxLance === 1) {
		          $.ajax({
		              url: url_site + 'save-lance.html',
		              type: 'post',
		              dataType: 'json',
		              beforeSend: function() {
		                 
		                  $('.disabled-lances').show();
		                  $.isAjaxLance = 0;
		              },
		              data: {
		                  lote_id: $id,
		                  updtime: upd,
		                  autoLance:$autoLance,
		                  autoLanceVal:$autoLanceVal,
		                  seconds: minutes_sec,
		                  end: date_ativo_finish
		              },
		              success: function(data) {
		            	  $('.disabled-lances').hide();
		                  if (data.error) {
		                      alert(data.message);
		                  } 
		              },
		              complete: function() {
		                  $.isAjaxLance = 1;
		              }
		          });
		      }
		  }
		  
	};
	
	
	$.fn.initLanceAuto = function(){
		
		$('[moneyMask]').maskMoney({
			    thousands: ".",
                decimal: ",",});
		
		$('[hasConfirmAutoLance]').off('click.hasConfirmAutoLance').on('click.hasConfirmAutoLance',function(e){
			e.preventDefault();
			var $val =  $('[moneyMask]').val(),
			    $u_id = $(this).attr('u-id'),
			    $l_id = $(this).attr('l-id'),
			    self = this;
			 
			  $.ajax({
				  'url': url_site + 'home/confirmAutoLance',
				  data:{'total':$val,'u-id':$u_id,'l-id':$l_id},
				  type:'POST',
                                  dataType:'json',  
				  beforeSend:function(){
					  $(self).attr('disabled','disabled');
				  },
				  complete:function(data){
					  var obj = $.parseJSON(data.responseText);
					  if(obj.error == false){
						 // window.location.reload();
						   $('.btn-lance-aut[l-id="'+$l_id+'"]').addClass('on');
						   $('.fancybox-close').trigger('click');
					  }
					  $(self).removeAttr('disabled');
					 // $('.fancybox-close').trigger('click');
				  }
			  });
		});
		
		$('[cancelAutoLance]').off('click.hasConfirmAutoLance').on('click.hasConfirmAutoLance',function(e){
			e.preventDefault();
			var $u_id = $(this).attr('u-id'),
			    $l_id = $(this).attr('l-id'),
			    self = this;
			 
			  $.ajax({
				  'url': url_site + 'home/cancelAutoLance',
				  data:{'u-id':$u_id,'l-id':$l_id},
				  type:'POST',
				  dataType:'json',
				  beforeSend:function(){
					  $(self).attr('disabled','disabled');
					
				  },
				  complete:function(data){
					  var obj = $.parseJSON(data.responseText);
					  if(obj.error == false){
						   
						   $('.fancybox-close').trigger('click');
						   $('.btn-lance-aut[l-id="'+$l_id+'"]').removeClass('on');
					  }
					  $(self).removeAttr('disabled');
					 
				  }
			  });
		});
		
	};
	
	jQuery.fn.watch = function( id, fn ) {
		 
	    return this.each(function(){
	 
	        var self = this;
	 
	        var oldVal = self[id];
	        $(self).data(
	            'watch_timer',
	            setInterval(function(){
	                if (self[id] !== oldVal) {
	                    fn.call(self, id, oldVal, self[id]);
	                    oldVal = self[id];
	                }
	            }, 100)
	        );
	 
	    });
	 
	    return self;
	};
	 
	jQuery.fn.unwatch = function( id ) {
	 
	    return this.each(function(){
	        clearInterval( $(this).data('watch_timer') );
	    });
	 
	};
	 
})(jQuery,window,document);

